import axios from "axios";
import { saveAs } from "file-saver";
import Cookies from "js-cookie";

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE,
});

service.interceptors.request.use((config) => {
  let token = Cookies.get("Admin-Token");
  if (token) {
    config.headers["Authorization"] = "Bearer " + token;
  }
  return config;
});

service.interceptors.response.use((res) => {
  let code = res.data.code || 200;
  if (code != 200) {
    ElMessage({
      type: "error",
      message: res.data.msg,
    });
    console.error(res.data.msg);
    return Promise.reject();
  } else {
    return res.data;
  }
});

const transParams = (params) => {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== "" &&
            typeof value[key] !== "undefined"
          ) {
            let params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
};

export let download = (url, params, filename, config) => {
  let loading = ElLoading.service({
    lock: true,
    text: "Downloading...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  return service
    .post(url, params, {
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
      transformRequest: [
        (params) => {
          return transParams(params);
        },
      ],
      ...config,
    })
    .then(async (data) => {
      let isBlob = data.type !== "application/json";
      if (isBlob) {
        let blob = new Blob([data]);
        saveAs(blob, filename);
      }

      loading.close();
      ElMessage({
        type: "success",
        message: "导出成功",
      });
    })
    .catch(() => {
      loading.close();
    });
};

export let upload = (url, file, callback) => {
  let loading = ElLoading.service({
    lock: true,
    text: "Uploading...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  let data = new FormData();
  data.append("file", file);
  return service
    .post(url, data, {
      headers: { "Content-Type": "multipart/form-data" },
    })
    .then((json) => {
      if (callback) callback(json);

      loading.close();
      ElMessage({
        type: "success",
        message: "导入成功",
      });
    })
    .catch(() => {
      loading.close();
    });
};

export default service;
